<template>
  <div class="paper-management-container">
    <!-- 搜索区域：仅管理员和审核员可见 -->
    <el-card v-if="!isTeacher" class="search-card">
      <div class="search-header">
        <h2>论文管理</h2>
        <el-button type="primary" @click="handleAddPaper">添加论文</el-button>
      </div>
      
      <!-- 搜索表单 -->
      <el-form :model="searchForm" inline class="search-form">
        <el-form-item label="教师姓名">
          <el-input v-model="searchForm.teacherName" placeholder="请输入教师姓名" clearable></el-input>
        </el-form-item>
        <el-form-item label="论文标题">
          <el-input v-model="searchForm.name" placeholder="请输入论文标题" clearable></el-input>
        </el-form-item>
        <el-form-item label="状态">
          <el-select v-model="searchForm.status" placeholder="请选择状态" clearable style="width: 120px;">
            <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">搜索</el-button>
          <el-button @click="resetSearch">重置</el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 教师视图：简化的头部 -->
    <el-card v-if="isTeacher" class="search-card">
      <div class="search-header">
        <h2>我的论文</h2>
        <el-button type="primary" @click="handleAddPaper">添加论文</el-button>
      </div>
    </el-card>

    <!-- 论文列表 -->
    <el-card class="list-card">
      <!-- 表格中移除论文类型列 -->
      <el-table 
        :data="paperList" 
        style="width: 100%" 
        v-loading="loading" 
        border
      >
        <el-table-column prop="id" label="ID" width="80" align="center"></el-table-column>
        <el-table-column prop="teacherName" label="教师姓名" min-width="100" v-if="!isTeacher"></el-table-column>
        <el-table-column prop="title" label="论文标题" min-width="200" show-overflow-tooltip></el-table-column>
        <el-table-column prop="journal" label="发表期刊" min-width="150" show-overflow-tooltip></el-table-column>
        <!-- 移除论文类型列 -->
        <el-table-column prop="impactFactor" label="影响因子" width="100" align="center"></el-table-column>
        <el-table-column prop="publishDate" label="发表日期" width="120" align="center"></el-table-column>
        <el-table-column prop="status" label="状态" width="100" align="center">
          <template #default="scope">
            <el-tag :type="getStatusType(scope.row.status)">{{ getStatusText(scope.row.status) }}</el-tag>
          </template>
        </el-table-column>
        <!-- 其他列保持不变 -->
      </el-table>
    </el-card>

    <!-- 添加/编辑论文对话框 -->
    <el-dialog 
      :title="dialogType === 'add' ? '添加论文' : '编辑论文'" 
      v-model="dialogVisible" 
      width="600px"
    >
      <el-form 
        :model="paperForm" 
        :rules="paperFormRules" 
        ref="paperFormRef" 
        label-width="100px"
      >
        <el-form-item label="教师" prop="teacherId" v-if="!isTeacher">
          <el-select v-model="paperForm.teacherId" placeholder="请选择教师" filterable style="width: 100%">
            <el-option 
              v-for="teacher in teacherOptions" 
              :key="teacher.id" 
              :label="teacher.realName + ' (' + teacher.department + ')'" 
              :value="teacher.id"
            ></el-option>
          </el-select>
        </el-form-item>
        <!-- 表单中移除论文类型字段 -->
        <el-form-item label="论文标题" prop="title">
          <el-input v-model="paperForm.title" placeholder="请输入论文标题"></el-input>
        </el-form-item>
        <el-form-item label="发表期刊" prop="journal">
          <el-input v-model="paperForm.journal" placeholder="请输入发表期刊"></el-input>
        </el-form-item>
        <el-form-item label="影响因子" prop="impactFactor">
          <el-input-number v-model="paperForm.impactFactor" :min="0" :precision="3" style="width: 100%"></el-input-number>
        </el-form-item>
        <el-form-item label="发表日期" prop="publishDate">
          <el-date-picker v-model="paperForm.publishDate" type="date" placeholder="选择发表日期" style="width: 100%" value-format="YYYY-MM-DD"></el-date-picker>
        </el-form-item>
        <el-form-item label="状态" prop="status">
        <el-select 
        v-model="paperForm.status" 
        placeholder="请选择状态" 
        style="width: 100%"
        :disabled="isTeacher">
        <el-option v-for="item in statusOptions" :key="item.value" :label="item.label" :value="item.value"></el-option>
        </el-select>
        <div v-if="isTeacher" class="status-note">
        <small>注：教师提交的论文默认为待审核状态</small>
        </div>
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="submitPaperForm" :loading="submitLoading">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted, computed } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import axios from 'axios'
import { useUserStore } from '../stores/user'

// 获取用户信息
const userStore = useUserStore()
const userRole = computed(() => userStore.userRole || localStorage.getItem('userRole'))
const isTeacher = computed(() => userRole.value === 'teacher')
const currentTeacherId = ref(null)

// 论文类型选项
// 移除论文类型选项和相关函数
// const paperTypeOptions = [
//   { value: 'sci', label: 'SCI' },
//   { value: 'ei', label: 'EI' },
//   { value: 'cssci', label: 'CSSCI' },
//   { value: 'other', label: '其他' }
// ]

// 移除获取论文类型标签和文本的函数
// const getPaperTypeTag = (type) => { ... }
// const getPaperTypeText = (type) => { ... }

// 搜索表单中移除type字段
const searchForm = reactive({
  teacherName: '',
  name: '',
  // 移除type字段
  status: ''
})

// 论文表单中移除type字段
const paperForm = reactive({
  id: null,
  teacherId: '',
  title: '',
  journal: '',
  // 移除type字段
  impactFactor: '',
  publishDate: '',
  status: 'pending'
})

// 论文表单验证规则中移除type字段
const paperFormRules = {
  teacherId: [
    { required: true, message: '请选择教师', trigger: 'change' }
  ],
  title: [
    { required: true, message: '请输入论文标题', trigger: 'blur' }
  ],
  journal: [
    { required: true, message: '请输入发表期刊', trigger: 'blur' }
  ],
  // 移除type字段验证规则
  impactFactor: [
    { required: true, message: '请输入影响因子', trigger: 'blur' }
  ],
  publishDate: [
    { required: true, message: '请选择发表日期', trigger: 'change' }
  ],
  status: [
    { required: true, message: '请选择状态', trigger: 'change' }
  ]
}

// 状态选项
const statusOptions = [
  { value: 'pending', label: '待审核' },
  { value: 'approved', label: '已通过' },
  { value: 'rejected', label: '已拒绝' }
]

// 获取论文类型标签
const getPaperTypeTag = (type) => {
  const typeMap = {
    'sci': 'danger',
    'ei': 'warning',
    'cssci': 'success',
    'other': 'info'
  }
  return typeMap[type] || 'info'
}

// 获取论文类型文本
const getPaperTypeText = (type) => {
  const typeMap = {
    'sci': 'SCI',
    'ei': 'EI',
    'cssci': 'CSSCI',
    'other': '其他'
  }
  return typeMap[type] || type
}

// 获取状态标签类型
const getStatusType = (status) => {
  const statusMap = {
    'pending': 'warning',
    'approved': 'success',
    'rejected': 'danger'
  }
  return statusMap[status] || 'info'
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    'pending': '待审核',
    'approved': '已通过',
    'rejected': '已拒绝'
  }
  return statusMap[status] || status
}


// 论文列表数据
const paperList = ref([])
const loading = ref(false)

// 教师选项
const teacherOptions = ref([])

// 对话框相关
const dialogVisible = ref(false)
const dialogType = ref('add') // 'add' 或 'edit'
const paperFormRef = ref(null)
const submitLoading = ref(false)





// 获取当前教师ID
const fetchCurrentTeacherId = async () => {
  if (isTeacher.value) {
    try {
      // 修正：从localStorage获取user并解析JSON
      let userId = userStore.userId
      if (!userId) {
        const userStr = localStorage.getItem('user')
        if (userStr) {
          try {
            const userObj = JSON.parse(userStr)
            userId = userObj.id
          } catch (e) {
            console.error('解析用户信息错误:', e)
          }
        }
      }
      
      if (userId) {
        const response = await axios.get(`http://localhost:8081/api/teacher/getByUserId?userId=${userId}`)
        if (response.data.code === 200 && response.data.data) {
          // 从返回的数据中获取教师ID
          currentTeacherId.value = response.data.data.teacher.id
        }
      } else {
        console.error('未找到用户ID')
      }
    } catch (error) {
      console.error('获取当前教师ID错误:', error)
    }
  }
}

// 获取论文列表
const fetchPaperList = async () => {
  loading.value = true
  try {
    const params = {}
    
    // 如果是教师角色，只查询自己的论文
    if (isTeacher.value && currentTeacherId.value) {
      params.teacherId = currentTeacherId.value
    } else {
      // 管理员或审核员可以按条件筛选
      params.teacherName = searchForm.teacherName
      params.title = searchForm.name
      params.journal = searchForm.journal
      params.status = searchForm.status
    }
    
    const response = await axios.post('http://localhost:8081/api/paper/list', params)
    if (response.data.code === 200) {
      // 处理返回的数据结构
      if (response.data.data && Array.isArray(response.data.data)) {
        // 如果是教师角色，手动筛选数据
        if (isTeacher.value && currentTeacherId.value) {
          paperList.value = response.data.data.filter(item => 
            item.paper && item.paper.teacherId === currentTeacherId.value
          ).map(item => ({
            id: item.paper.id,
            teacherId: item.paper.teacherId,
            teacherName: item.teacherName,
            departmentName: item.departmentName,
            title: item.paper.title,
            journal: item.paper.journal,
            impactFactor: item.paper.impactFactor,
            publishDate: item.paper.publishDate,
            status: item.paper.status
          }));
        } else {
          paperList.value = response.data.data.map(item => ({
            id: item.paper.id,
            teacherId: item.paper.teacherId,
            teacherName: item.teacherName,
            departmentName: item.departmentName,
            title: item.paper.title,
            journal: item.paper.journal,
            impactFactor: item.paper.impactFactor,
            publishDate: item.paper.publishDate,
            status: item.paper.status
          }));
        }
      } else {
        paperList.value = [];
      }
    } else {
      ElMessage.error(response.data.msg || '获取论文列表失败')
    }
  } catch (error) {
    console.error('获取论文列表错误:', error)
    ElMessage.error('获取论文列表失败，请检查网络连接')
  } finally {
    loading.value = false
  }
}

// 获取教师列表（用于下拉选择）
const fetchTeacherOptions = async () => {
  // 如果是教师角色，不需要获取教师列表
  if (isTeacher.value) return
  
  try {
    const response = await axios.post('http://localhost:8081/api/teacher/list', {})
    if (response.data.code === 200) {
      teacherOptions.value = response.data.data.map(item => ({
        id: item.teacher.id,
        realName: item.user.realName,
        department: item.teacher.department
      }))
    } else {
      ElMessage.error(response.data.msg || '获取教师列表失败')
    }
  } catch (error) {
    console.error('获取教师列表错误:', error)
    ElMessage.error('获取教师列表失败，请检查网络连接')
  }
}

// 搜索论文
const handleSearch = () => {
  fetchPaperList()
}

// 重置搜索
const resetSearch = () => {
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = ''
  })
  fetchPaperList()
}

// 添加论文
const handleAddPaper = () => {
  dialogType.value = 'add'
  resetPaperForm()
  
  // 如果是教师角色，自动设置教师ID
  if (isTeacher.value && currentTeacherId.value) {
    paperForm.teacherId = currentTeacherId.value
  }
  
  dialogVisible.value = true
}

// 编辑论文函数
const handleEditPaper = (row) => {
  dialogType.value = 'edit'
  paperForm.id = row.id
  paperForm.teacherId = row.teacherId
  paperForm.title = row.title
  paperForm.journal = row.journal
  paperForm.impactFactor = row.impactFactor
  paperForm.publishDate = row.publishDate
  paperForm.status = row.status
  
  dialogVisible.value = true
}

// 重置论文表单中移除type字段
const resetPaperForm = () => {
  if (paperFormRef.value) {
    paperFormRef.value.resetFields()
  }
  
  paperForm.id = null
  paperForm.teacherId = ''
  paperForm.title = ''
  paperForm.journal = ''
  // 移除type字段重置
  paperForm.impactFactor = ''
  paperForm.publishDate = ''
  paperForm.status = 'pending'
}

// 提交论文表单中移除type字段
const submitPaperForm = () => {
  // 如果是教师角色，确保使用当前教师ID和待审核状态
  if (isTeacher.value && currentTeacherId.value) {
    paperForm.teacherId = currentTeacherId.value
    paperForm.status = 'pending' // 教师提交的论文始终为待审核状态
  }
  
  paperFormRef.value.validate(async (valid) => {
    if (valid) {
      submitLoading.value = true
      try {
        const url = dialogType.value === 'add' 
          ? 'http://localhost:8081/api/paper/add' 
          : 'http://localhost:8081/api/paper/update'
        
        const response = await axios.post(url, {
          id: paperForm.id,
          teacherId: paperForm.teacherId,
          title: paperForm.title,
          journal: paperForm.journal,
          // 移除type字段
          impactFactor: paperForm.impactFactor,
          publishDate: paperForm.publishDate,
          status: paperForm.status
        })
        
        if (response.data.code === 200) {
          ElMessage.success(dialogType.value === 'add' ? '添加论文成功' : '编辑论文成功')
          dialogVisible.value = false
          fetchPaperList() // 刷新列表
        } else {
          ElMessage.error(response.data.msg || (dialogType.value === 'add' ? '添加论文失败' : '编辑论文失败'))
        }
      } catch (error) {
        console.error(dialogType.value === 'add' ? '添加论文错误:' : '编辑论文错误:', error)
        ElMessage.error(dialogType.value === 'add' ? '添加论文失败，请检查网络连接' : '编辑论文失败，请检查网络连接')
      } finally {
        submitLoading.value = false
      }
    }
  })
}

// 删除论文
const handleDeletePaper = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除论文 "${row.title}" 吗？此操作将不可逆！`,
      '删除论文',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const params = new URLSearchParams()
    params.append('id', row.id)
    
    const response = await axios.post('http://localhost:8081/api/paper/delete', params)
    
    if (response.data.code === 200) {
      ElMessage.success('删除论文成功')
      fetchPaperList() // 刷新列表
    } else {
      ElMessage.error(response.data.msg || '删除论文失败')
    }
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除论文错误:', error)
      ElMessage.error('删除论文失败，请检查网络连接')
    }
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchCurrentTeacherId()
  fetchPaperList()
  fetchTeacherOptions()
})
</script>

<style scoped>
.paper-management-container {
  padding: 20px;
}

.search-card {
  margin-bottom: 20px;
}

.search-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.search-form {
  margin-top: 15px;
}

.list-card {
  margin-bottom: 20px;
}

.operation-buttons {
  display: flex;
  justify-content: center;
  gap: 10px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
}

:deep(.el-table) {
  border-radius: 4px;
  overflow: hidden;
}

:deep(.el-table th) {
  background-color: #f5f7fa;
  color: #606266;
  font-weight: bold;
}

:deep(.el-table--border .el-table__cell) {
  border-right: 1px solid #ebeef5;
}

:deep(.el-table__row:hover td) {
  background-color: #f5f7fa;
}
</style>